const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')

const app = express()
const PORT = 3002

app.use(cors())
app.use(bodyParser.json())

// 添加错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack)
  res.status(500).json({ error: 'Internal Server Error' })
})

// 生成实时广告数据
function generateRealTimeData() {
  const now = new Date()
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  const currentTime = `${hours}:${minutes}`

  // 基础值加随机波动
  const baseExposure = 10000 + Math.floor(Math.random() * 5000)
  const baseClicks = 1000 + Math.floor(Math.random() * 500)

  return {
    exposure: [
      { date: currentTime, value: baseExposure },
      { date: currentTime, value: baseExposure * 0.9 },
      { date: currentTime, value: baseExposure * 0.8 }
    ],
    clicks: [
      { date: currentTime, value: baseClicks },
      { date: currentTime, value: baseClicks * 0.9 },
      { date: currentTime, value: baseClicks * 0.8 }
    ]
  }
}

// API路由
app.get('/api/ads', (req, res) => {
  const { range = 'realtime' } = req.query
  let data

  if (range === 'hourly') {
    data = generateHourlyData()
  } else if (range === 'daily') {
    data = generateDailyData()
  } else {
    data = generateRealTimeData()
  }

  res.json(data)
})

function generateHourlyData() {
  const data = []

  // 生成过去24小时的数据
  for (let i = 23; i >= 0; i--) {
    const now = new Date()
    now.setHours(now.getHours() - i)

    const hour = now.getHours().toString().padStart(2, '0')
    const month = now.getMonth() + 1
    const day = now.getDate()
    const dateStr = `${month}月${day}日 ${hour}:00`

    // 生成基于时间的真实数据模式
    let baseValue = 5000
    const hourOfDay = now.getHours()

    // 添加时段效应：9-18点是广告投放高峰期
    if (hourOfDay >= 9 && hourOfDay <= 18) {
      baseValue = 8000 + Math.floor(Math.random() * 6000)
    } else if (hourOfDay >= 19 && hourOfDay <= 22) {
      baseValue = 6000 + Math.floor(Math.random() * 4000) // 晚间也有一定投放
    } else {
      baseValue = 2000 + Math.floor(Math.random() * 3000) // 深夜和早晨较少
    }

    data.push({
      date: dateStr,
      value: baseValue
    })
  }

  return {
    exposure: data,
    clicks: data.map(item => ({
      date: item.date,
      value: Math.floor(item.value * (0.08 + Math.random() * 0.04)) // 8-12%的点击率
    }))
  }
}

function generateDailyData() {
  const data = []

  // 生成从2024年10月到2025年3月的数据
  const startDate = new Date(2024, 9, 1) // 2024年10月1日 (月份从0开始)
  const endDate = new Date(2025, 2, 31)  // 2025年3月31日

  const currentDate = new Date(startDate)

  while (currentDate <= endDate) {
    const month = currentDate.getMonth() + 1
    const day = currentDate.getDate()
    const dateStr = `${month}月${day}日`

    // 生成基础数据，添加一些季节性变化
    let baseValue = 10000

    // 添加季节性变化：假设10-12月广告投放较多，1-3月较少
    if (month >= 10 && month <= 12) {
      baseValue = 12000 + Math.floor(Math.random() * 8000) // 较高的广告投放
    } else if (month >= 1 && month <= 3) {
      baseValue = 8000 + Math.floor(Math.random() * 6000)  // 年后较低的投放
    }

    // 添加周末效应：周末广告效果通常不同
    const dayOfWeek = currentDate.getDay()
    if (dayOfWeek === 0 || dayOfWeek === 6) { // 周末
      baseValue = Math.floor(baseValue * 0.8)
    }

    data.push({
      date: dateStr,
      value: baseValue
    })

    // 移动到下一天
    currentDate.setDate(currentDate.getDate() + 1)
  }

  return {
    exposure: data,
    clicks: data.map(item => ({
      date: item.date,
      value: Math.floor(item.value * (0.08 + Math.random() * 0.04)) // 8-12%的点击率
    }))
  }
}

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`)
})
